package edu.ncst.baseweb.service.impl.equ;

import cn.wintersun.basecommon.common.Result;
import edu.ncst.baseweb.dao.equ.EquClass;
import edu.ncst.baseweb.mapper.EquClassMapper;
import edu.ncst.baseweb.mapper.EquMapper;
import edu.ncst.baseweb.service.intrer.equ.EquClassService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EquClassServiceImpl implements EquClassService {
    @Autowired
    private EquClassMapper equClassMapper;

    @Autowired
    private EquMapper equMapper;
    @Override
    public Result<IPage<EquClass>> list(EquClass equClass) {

        //创建查询条件0
        QueryWrapper<EquClass> queryWrapper = Wrappers.query();
        //根据id排序
        queryWrapper.orderBy(true,true,"id");
        //查询条件
        //设备类型名称
        if(StringUtils.isNotEmpty(equClass.getName())){
            queryWrapper.like(EquClass.COL_NAME,equClass.getName());
        }
        //设备编号
        if(StringUtils.isNotEmpty(equClass.getClassCode())){
            queryWrapper.like(EquClass.COL_CODE,equClass.getClassCode());
        }
        //创建页数
        Page<EquClass> userPage = new Page<>(equClass.getCurrent(), equClass.getPageSize());
        Page<EquClass> equClassPage = equClassMapper.selectPage(userPage, queryWrapper);
        //获取设备数量
        List<EquClass> records = equClassPage.getRecords();
        for (EquClass record : records) {
            Integer num = equMapper.countByClassId(record.getId());
            record.setNum(num);
            equClassMapper.updateById(record);
        }

        //equClassPage.setRecords(records);
        return Result.ok(equClassPage);
    }



    @Override
    public Result<Object> save(EquClass equ) {
        //新增
        if(equ.getId()==null){
            equClassMapper.insert(equ);
        }
        //修改逻辑
        else{
            equClassMapper.updateById(equ);
        }
        return Result.ok();
    }

    @Override
    public Result<Object>  delete(String classId) throws Exception {
        if(classId==null){
            throw new Exception("被删除的设备不存在");
        }
        QueryWrapper<EquClass> query =Wrappers.query();
        query.eq("id",classId);
        EquClass equClass = equClassMapper.selectOne(query);
        if (equClass.getNum()>0){
            return Result.failure(500,"该类型还有设备存在");
        }else {
            List<String> ids = Arrays.stream(classId.split(",")).collect(Collectors.toList());
            equClassMapper.deleteBatchIds(ids);
            //返回
            return Result.failure(200, "删除成功！");
        }
    }
}
